package com.wll.okhttpcode;

import android.content.Context;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okio.Buffer;

/**
 * created by detachment on 2020/11/24
 */
public class HttpsUtils {

    public static SSLParams getSSLSocketFactory(Context context) {
        //创建X.509格式的CertificateFactory
        CertificateFactory cf = null;
        try {
            cf = CertificateFactory.getInstance("X.509");
            //从asserts中获取证书的流 //SRCA.cer
//            InputStream cerInputStream = context.getAssets().open("scra.cer;
            InputStream cerInputStream = new Buffer().writeUtf8(cer12306).inputStream();
            //ca是java.security.cert.Certificate，不是java.security.Certificate，
            //也不是javax.security.cert.Certificate
            Certificate ca;
            try {
                //证书工厂根据证书文件的流生成证书Certificate
                ca = cf.generateCertificate(cerInputStream);
                System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
            } finally {
                cerInputStream.close();
            }

            // 创建一个默认类型的KeyStore，存储我们信任的证书
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            //将证书ca作为信任的证书放入到keyStore中
            keyStore.setCertificateEntry("ca", ca);

            //TrustManagerFactory是用于生成TrustManager的，我们创建一个默认类型的TrustManagerFactory
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            //用我们之前的keyStore实例初始化TrustManagerFactory，这样tmf就会信任keyStore中的证书
            tmf.init(keyStore);
            //通过tmf获取TrustManager数组，TrustManager也会信任keyStore中的证书
            TrustManager[] trustManagers = tmf.getTrustManagers();

            //创建TLS类型的SSLContext对象， that uses our TrustManager
            SSLContext sslContext = SSLContext.getInstance("TLS");
            //用上面得到的trustManagers初始化SSLContext，这样sslContext就会信任keyStore中的证书
            sslContext.init(null, trustManagers, null);

            //通过sslContext获取SSLSocketFactory对象
            //将sslSocketFactory通过setSSLSocketFactory方法作用于HttpsURLConnection对象
            //这样conn对象就会信任我们之前得到的证书对象
            SSLParams sslParams = new SSLParams();
            sslParams.sSLSocketFactory = sslContext.getSocketFactory();
            sslParams.trustManager = chooseTrustManager(trustManagers);
            return sslParams;
        } catch (CertificateException | IOException | KeyStoreException
                | NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static class SSLParams {
        public SSLSocketFactory sSLSocketFactory;
        public X509TrustManager trustManager;
    }

    private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
        for (TrustManager trustManager : trustManagers) {
            if (trustManager instanceof X509TrustManager) {
                return (X509TrustManager) trustManager;
            }
        }
        return null;
    }

    private static String cer12306 = "-----BEGIN CERTIFICATE-----\n" +
            "MIIGhTCCBW2gAwIBAgIQA+MUe4zi0jWRXlnl10ptQzANBgkqhkiG9w0BAQsFADBN\n" +
            "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMScwJQYDVQQDEx5E\n" +
            "aWdpQ2VydCBTSEEyIFNlY3VyZSBTZXJ2ZXIgQ0EwHhcNMTgxMDIzMDAwMDAwWhcN\n" +
            "MjEwMTA3MTIwMDAwWjBZMQswCQYDVQQGEwJDTjEQMA4GA1UEBxMHQmVpamluZzEW\n" +
            "MBQGA1UEChMNQ0hJTkEgUkFJTFdBWTELMAkGA1UECxMCSVQxEzARBgNVBAMMCiou\n" +
            "MTIzMDYuY24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDs+CFFoqIr\n" +
            "Iy+/Xt5JFf3VLQJaDwPr8lY/bjdmWVhT++sVMhGdvXsk5cn3iPoAaTxLgUbKUWDK\n" +
            "B5KSTJkkF4IGDYPgqxuX8YMEROyBRyINA0tgL0IvOPMXIDfjV1AklBpR4TblQTiO\n" +
            "l6IBzRzdujT0J1lTNIOUibNSPbVvL0m9po8kKh2VW7EV68KIxE/fwL8ClCZg57Cl\n" +
            "/ipvz9g8I+yJA7IBcWMOkFQfbANxMgsgmP1+HT+yUyTOLvwgB8iY23vYEw7bxXTy\n" +
            "ZOcbU3ScFES0BNgTQhZLHAFwB/iuCDXa75IJcPXwv53bcEUcO4tPhzqlyy+Y9lL4\n" +
            "3pom/SmIBOI1AgMBAAGjggNTMIIDTzAfBgNVHSMEGDAWgBQPgGEcgjFh1S8o541G\n" +
            "OLQs4cbZ4jAdBgNVHQ4EFgQU1bLep0Ynjkzfp+wusYZICzSWADAwFQYDVR0RBA4w\n" +
            "DIIKKi4xMjMwNi5jbjAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUH\n" +
            "AwEGCCsGAQUFBwMCMGsGA1UdHwRkMGIwL6AtoCuGKWh0dHA6Ly9jcmwzLmRpZ2lj\n" +
            "ZXJ0LmNvbS9zc2NhLXNoYTItZzYuY3JsMC+gLaArhilodHRwOi8vY3JsNC5kaWdp\n" +
            "Y2VydC5jb20vc3NjYS1zaGEyLWc2LmNybDBMBgNVHSAERTBDMDcGCWCGSAGG/WwB\n" +
            "ATAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2VydC5jb20vQ1BTMAgG\n" +
            "BmeBDAECAjB8BggrBgEFBQcBAQRwMG4wJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3Nw\n" +
            "LmRpZ2ljZXJ0LmNvbTBGBggrBgEFBQcwAoY6aHR0cDovL2NhY2VydHMuZGlnaWNl\n" +
            "cnQuY29tL0RpZ2lDZXJ0U0hBMlNlY3VyZVNlcnZlckNBLmNydDAMBgNVHRMBAf8E\n" +
            "AjAAMIIBfgYKKwYBBAHWeQIEAgSCAW4EggFqAWgAdgC72d+8H4pxtZOUI5eqkntH\n" +
            "OFeVCqtS6BqQlmQ2jh7RhQAAAWagPzF3AAAEAwBHMEUCIQCmZTuyoLGRQ3dzYzGB\n" +
            "nKaeM2xQudJ5zPdHsszeh12rawIgPUGozd4otgOnaUtI/ghvNM8diu0Xz/OqmQV2\n" +
            "LxLJgIAAdQCHdb/nWXz4jEOZX73zbv9WjUdWNv9KtWDBtOr/XqCDDwAAAWagPzFs\n" +
            "AAAEAwBGMEQCICeb6M3/6zR2RH8JscywG2KCTWYPWzDuBWms9cpMnDMyAiAwNvBC\n" +
            "f0iOJNYGDP5Jv4XFvKFlHrY/t29VxZ+p/ci8yQB3AG9Tdqwx8DEZ2JkApFEV/3cV\n" +
            "HBHZAsEAKQaNsgiaN9kTAAABZqA/MesAAAQDAEgwRgIhAJfrIpo6xhWAJDtE9IlJ\n" +
            "XyvBnZYh52V/WZ8G71XPtsvGAiEAxNYqMB2bp3PBh+2/bUZlPA6e/vsiXVNEyn4W\n" +
            "8T6rivEwDQYJKoZIhvcNAQELBQADggEBALu12tl9kHozvMVAVeEg/OFcYSXcwiPU\n" +
            "K4tRiJKOEZnolJbs3tAznqT6tw+3W3YCrI6+/mhuGkK4lqUuq3CFwa/2lFsWr3bh\n" +
            "UPh6OJMGzL6XgasrLhf/A2EqUMeNZMe5cJx4o2e37jZ7Nsait6DScGClD6/e8ziZ\n" +
            "X2yhiJ1KJc8qXmPRpfbATSKKuFS6ijYX+5BDgYufS3VeR6eQmwn0pNn3ZIH0KDWE\n" +
            "207WOLDHqYEEEj10WNzCBisX2O35UGm4dZQ/kvYvKX3THXIWWPFUmgBexo84RZew\n" +
            "Fi0RF/XDnTk/4+Pwn+FELqwuF8UjPJPJ0zL9pzzk+jeWh4zuKrqQ2Cs=\n" +
            "-----END CERTIFICATE-----";
}
